package fl.ass.service.service.impl;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.Pager;
import cmm.service.core.framework.biz.BaseBizImpl;
import cmm.service.core.framework.dao.IBaseDao;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.project.constant.PrjPrdDtlConstant;
import cn.fl.sue.api.ISueApplyViewApiService;
import cn.fl.sue.condition.SueApplyViewQC;
import cn.fl.sue.constant.SueDicCode;
import cn.fl.sue.dto.SueApplyViewDTO;
import com.alibaba.fastjson.JSON;
import com.lionbridge.activiti.WorkflowClient;
import fl.ass.facade.condition.AssDealCarQueryCondition;
import fl.ass.facade.constant.InterfaceConstants;
import fl.ass.facade.dto.AssDealCarDTO;
import fl.ass.facade.dto.AssTrailCarDDTO;
import fl.ass.facade.dto.ProductStatusLogDTO;
import fl.ass.service.config.NacosConfiguration;
import fl.ass.service.dao.AssDealCarMapper;
import fl.ass.service.po.AssDealCar;
import fl.ass.service.service.IAssDealCarService;
import fl.ass.service.service.IAssTrailCarDService;
import fl.ass.service.service.IAssTrailCarMService;
import fl.ass.service.transform.AssDealCarTransform;
import fl.flow.facade.flow.dto.SysFlowSHDTO;
import fl.flow.service.flow.service.ISysFlowSHService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import veh.src.facade.src.src.api.IVehSrcInfQueryApiService;
import veh.src.facade.src.src.condition.VehSrcInfQC;
import veh.src.facade.src.src.dto.VehSrcInfDTO;

import java.util.*;

/**
 * @Description: 处置-转优车信息表 服务层接口实现
 * @Description: 类中已经实现了简单增删改查操作,可以直接使用,如果有需要重写该方法即可：
 * @Description: 1、add(TVO entity) 2、removeById(Long id) 3、modify(DTO entity) 4、selectById(Long id)	5、searchListPage(Pager page) 7、searchList(DTO dto)   
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class AssDealCarServiceImpl extends BaseBizImpl<AssDealCar, AssDealCarDTO, AssDealCarQueryCondition> implements IAssDealCarService {
	
	@SuppressWarnings("unused")
	private static final Logger logger = LoggerFactory.getLogger(IAssDealCarService.class);
	
	@Autowired
	private AssDealCarMapper assDealCarMapper;
	
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;

    @Autowired
    private ISueApplyViewApiService sueApplyViewApiService;

    @Autowired
    private ISysFlowSHService sysFlowSHService;

    @Autowired
    private IAssTrailCarDService assTrailCarDService;

    /**
     * 车型库的服务
     */
    @Autowired
    private IVehSrcInfQueryApiService vehSrcInfQueryApiService;

    @Autowired
    private IAssTrailCarMService assTrailCarMService;

    @Autowired
    private NacosConfiguration nacosConfiguration;
	
	@Override
	public List<AssDealCarDTO> searchList(AssDealCarQueryCondition condition) throws BaseException {
		if(null == condition) return new ArrayList<AssDealCarDTO>();
		List<AssDealCar> list = this.assDealCarMapper.selectList(condition);
		return AssDealCarTransform.toDTOList(list);
	}
	
	@Override
	public IBaseDao<AssDealCar,AssDealCarQueryCondition> getDao() {
		return this.assDealCarMapper;
	}

	/* (non-Javadoc)
	 * @see fl.ass.service.service.IAssDealCarService#findAssDealCarListByPage(cmm.mid.core.framework.page.Pager)
	 */
	@Override
	public Pager findAssDealCarListByPage(Pager page) {
		List<AssDealCarDTO> list = this.assDealCarMapper.findAssDealCarListByPage(page);
		if(!CollectionUtils.isNotEmpty(list)){
			list = new ArrayList<AssDealCarDTO>();
		}
		SysDictionaryDTO dictionary = null;
		for(AssDealCarDTO dto : list){
			//处理拖车状态
			if(StringUtils.isNotBlank(dto.getBackStsCd())){
				dictionary = sysDictionaryApiService.getCode(InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE, InterfaceConstants.BACK_STATUS_CD, dto.getBackStsCd());
				if(null != dictionary){
					dto.setBackStsCd(dictionary.getCodeNm());
				}
			}
			//处理处置状态
			if(StringUtils.isNotBlank(dto.getDealStsCd())){
				dictionary = sysDictionaryApiService.getCode(InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE, InterfaceConstants.DEAL_STATUS_CD, dto.getDealStsCd());
				if(null != dictionary){
					dto.setDealStsCd(dictionary.getCodeNm());
				}
			}
			//处理评价状态
			if(StringUtils.isNotBlank(dto.getEvalStatusCd())){
				dictionary = sysDictionaryApiService.getCode(InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE, InterfaceConstants.EVAL_STATUS_CD, dto.getEvalStatusCd());
				if(null != dictionary){
					dto.setEvalStatusCd(dictionary.getCodeNm());
				}
			}
			//处理组织机构名称和事业部简码
			if(StringUtils.isNotBlank(dto.getBuOrgCd())){
				dictionary = sysDictionaryApiService.getCode(InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE, InterfaceConstants.BUSINESS_ORG_CD, dto.getBuOrgCd());
				if(null != dictionary){
					dto.setOrgName(dictionary.getCodeDesc());
					dto.setOrgSimpleCode(dictionary.getCodeNm());
				}
			}
			//处理拖回标记
			if(StringUtils.isNotBlank(dto.getBackedFlagCd())){
				dictionary = sysDictionaryApiService.getCode(InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE, InterfaceConstants.BACK_FLAG_CD, dto.getBackedFlagCd());
				if(null != dictionary){
					dto.setBackedFlagCd(dictionary.getCodeNm());
				}
			}else{
				dto.setBackedFlagCd("未标记");
			}
            // 根据项目id获取最近的一条诉讼申请数据
            if (StringUtils.isNotEmpty(dto.getPrjId())) {
                SueApplyViewQC qc = new SueApplyViewQC();
                qc.setDataId(dto.getPrjId());
                SueApplyViewDTO sueApplyViewDTO = this.sueApplyViewApiService.selectLatestSueApplyView(qc);
                if (null != sueApplyViewDTO && StringUtils.isNotEmpty(sueApplyViewDTO.getSueStsCd())) {
                    dictionary = sysDictionaryApiService.getCode(InterfaceConstants.SYS_CODE, InterfaceConstants.ORG_CODE, SueDicCode.SUE0007, sueApplyViewDTO.getSueStsCd());
                    if (null != dictionary) {
                        dto.setSueStsCd(sueApplyViewDTO.getSueStsCd());
                        dto.setSueStsNm(dictionary.getCodeNm());
                    }
                }
            }
            // 根据车架号查询车源信息
            if (StringUtils.isNotEmpty(dto.getPrdVin())) {
                // 车型
                VehSrcInfQC qc = new VehSrcInfQC();
                qc.setVin(dto.getPrdVin());
                List<VehSrcInfDTO> vehSrcInfDTOS = vehSrcInfQueryApiService.searchVehSrcInfDTOList(qc);
                if (CollectionUtils.isNotEmpty(vehSrcInfDTOS)) {
                    VehSrcInfDTO vehSrcInfDTO = vehSrcInfDTOS.get(0);
                    Long vehId = vehSrcInfDTO.getId();
                    vehSrcInfDTO = vehSrcInfQueryApiService.selectVehSrcInfDTOById(vehId);
                    dto.setCarSrcNo(vehSrcInfDTO.getCarNo());
                }
            }
		}
		page.setResultList(list);
		return page;
	}
	
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public Long saveAssDealCar(AssDealCarDTO dto) {
		AssDealCar po = AssDealCarTransform.toPO(dto);
		if(null != po){
			assDealCarMapper.insert(po);
			Long id = po.getId();
			if(null != id){
				//判断支付表ID是否为空
				Long paySchId = po.getPaySchId();
				if(null != paySchId){
					//修改原转优车信息数据的历史状态
					assDealCarMapper.updateAssDealCarHisStatus(paySchId, id);
				}
			}
			return id;
		}
		return null;
	}

	@Override
	@Transactional(readOnly = true)
	public List<AssDealCar> searchUnionListByPage(Pager page) throws BaseException {
		return assDealCarMapper.searchUnionListByPage(page);
	}

    @Override
    public void autoEndDealCarFlow() throws BaseException {
	    BaseLogUtils.newLogger("自动处理超期转优车开始").info();
	    try {
            AssDealCarQueryCondition condition = new AssDealCarQueryCondition();
            condition.setExpireTime(DateUtils.getCurrentDate(DateUtils.YYYY_MM_DD));
            condition.setIsDel(BaseConstant.IS_YESNO_NO);
            condition.setFlowStatusCd(InterfaceConstants.FLOW_STATUS_CD_2);
            List<String> taskDefKeyList = new ArrayList(6);
            taskDefKeyList.add(InterfaceConstants.DEAL_CAR_FLOW_TASK_KEY_1);
            taskDefKeyList.add(InterfaceConstants.DEAL_CAR_FLOW_TASK_KEY_2);
            taskDefKeyList.add(InterfaceConstants.DEAL_CAR_FLOW_TASK_KEY_3);
            taskDefKeyList.add(InterfaceConstants.DEAL_CAR_FLOW_TASK_KEY_4);
            taskDefKeyList.add(InterfaceConstants.DEAL_CAR_FLOW_TASK_KEY_5);
            taskDefKeyList.add(InterfaceConstants.DEAL_CAR_FLOW_TASK_KEY_6);
            condition.setTaskDefKeyList(taskDefKeyList);
            List<AssDealCarDTO> assDealCarDTOS = this.searchList(condition);
            if (CollectionUtils.isEmpty(assDealCarDTOS)) {
                BaseLogUtils.newLogger("无超期可结束转优车流程").info();
                return;
            }
            // 需要结束的流程历史
            List<SysFlowSHDTO> sysFlowSHDTOS = new ArrayList<>(assDealCarDTOS.size());
            // 需要修改的支付表状态
            List<ProductStatusLogDTO> dtos = new ArrayList<>(assDealCarDTOS.size());
            for (AssDealCarDTO assDealCarDTO : assDealCarDTOS) {
                SysFlowSHDTO sysFlowSHDTO = new SysFlowSHDTO();
                sysFlowSHDTO.setDataId(assDealCarDTO.getId());
                sysFlowSHDTO.setAudStsCd("2");
                sysFlowSHDTO.setpMdfTm(new Date());
                sysFlowSHDTO.setMdfUsrId(1L);
                sysFlowSHDTO.setMdfTm(new Date());
                sysFlowSHDTOS.add(sysFlowSHDTO);
                // 结束转优车工作流
                DataResultDTO dataResultDTO = endDealCarActiviti(assDealCarDTO.getProcId(), "pass", assDealCarDTO.getTaskDefKey());
                BaseLogUtils.newLogger("procId=" + assDealCarDTO.getProcId() + "结束转优车工作流返回数据:" + JSON.toJSONString(dataResultDTO)).info();
                if (BaseConstant.IS_YESNO_NO_STR.equals(dataResultDTO.getCode())) {
                    throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_700, "结束转优车工作流失败！");
                }
                // 处理转优车数据，得到需要修改的流程历史并结束工作流
                assDealCarDTO.setFlowStatusCd(InterfaceConstants.FLOW_STATUS_CD_3);
                assDealCarDTO.setIsAssign(BaseConstant.IS_YESNO_NO);
                assDealCarDTO.setTaskDefKey("");
                assDealCarDTO.setTaskDefKeyNm("");
                assDealCarDTO.setDealTm(new Date());
                assDealCarDTO.setMdfUsrId(1L);
                assDealCarDTO.setMdfTm(new Date());
                modify(assDealCarDTO);
                // 处理拖车明细数据
                AssTrailCarDDTO assTrailCarDDTO = this.assTrailCarDService.selectById(assDealCarDTO.getDetailId());
                assTrailCarDDTO.setDealStsCd(InterfaceConstants.DEAL_STATUS_CD_11);
                this.assTrailCarDService.modify(assTrailCarDDTO);
                // 同步修改疫情支付表状态
                ProductStatusLogDTO productStatusLogDTO = new ProductStatusLogDTO();
                productStatusLogDTO.setPaySchId(assTrailCarDDTO.getPaySchId());
                productStatusLogDTO.setPrjPrdId(assTrailCarDDTO.getPrjPrdDtlId());
                productStatusLogDTO.setCurrentStatus(PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_20);
                productStatusLogDTO.setOpCode(InterfaceConstants.OP_CODE_OP0029);
                productStatusLogDTO.setProcessInstanceCode(assDealCarDTO.getProcNo());
                productStatusLogDTO.setProcessInstanceId(assDealCarDTO.getProcId());
                this.assTrailCarMService.updateYQPrdStsCdByFlow(productStatusLogDTO);
            }
            this.batchUpdateDealCarFlowAudStatus(sysFlowSHDTOS);
            this.updatePayStatus(dtos, assDealCarDTOS);
            BaseLogUtils.newLogger("自动处理超期转优车结束").info();
        } catch (BaseException e) {
            BaseLogUtils.newLogger("自动结束超期转优车流程失败").setThrowable(e).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        } catch (Exception e) {
            BaseLogUtils.newLogger("自动结束超期转优车流程失败").setThrowable(e).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            throw e;
        }
    }

    /**
     * 修改支付表状态
     * @param productStatusLogDTOS
     * @param assDealCarDTOS
     * @return
     */
    private void updatePayStatus(List<ProductStatusLogDTO> productStatusLogDTOS, List<AssDealCarDTO> assDealCarDTOS) {
        for (AssDealCarDTO assDealCarDTO : assDealCarDTOS) {
            AssTrailCarDDTO assTrailCarDDTO = this.assTrailCarDService.selectById(assDealCarDTO.getDetailId());
            if (null == assDealCarDTO) {
                throw new BaseException("无法查询拖车明细信息");
            }
            ProductStatusLogDTO proDTO = new ProductStatusLogDTO();
            proDTO.setPreStatus(InterfaceConstants.PAY_STATUS_CD_S01060203);
            proDTO.setCurrentStatus(InterfaceConstants.PAY_STATUS_CD_S0106020301);
            proDTO.setPrjPrdId(assTrailCarDDTO.getPrjPrdDtlId());
            proDTO.setOpCode(InterfaceConstants.OP_CODE_OP0029);
            productStatusLogDTOS.add(proDTO);
        }
        assTrailCarDService.updatePayStatus(productStatusLogDTOS);
    }

    /**
     * 自动结束转优车工作流
     * @param pInstId 流程实例id
     * @param passCd
     * @param taskDefKey
     * @return
     */
    private DataResultDTO endDealCarActiviti(String pInstId, String passCd, String taskDefKey) {
        DataResultDTO result = new DataResultDTO(String.valueOf(BaseConstant.IS_YESNO_YES), "操作成功!");
        try {
            if(StringUtils.isEmpty(pInstId)){
                result.setCode(String.valueOf(BaseConstant.IS_YESNO_NO));
                result.setInfo("流程实例ID不能为空!");
                return result;
            }
            Map<String,Object> params = new HashMap<String,Object>();
            if(StringUtils.isEmpty(taskDefKey)){
                result.setCode(String.valueOf(BaseConstant.IS_YESNO_NO));
                result.setInfo("流程所在节点定义key不能为空!");
                return result;
            } else {
                switch (taskDefKey) {
                    case InterfaceConstants.DEAL_CAR_FLOW_TASK_KEY_1:
                        params.put("pass", BaseConstant.IS_YESNO_NO);
                        break;
                    case InterfaceConstants.DEAL_CAR_FLOW_TASK_KEY_2:
                        params.put("assignFlag", BaseConstant.IS_YESNO_NO);
                        break;
                    case InterfaceConstants.DEAL_CAR_FLOW_TASK_KEY_3:
                        params.put("operateKey", "FLOW_0000_020_001_004_002");
                        break;
                    case InterfaceConstants.DEAL_CAR_FLOW_TASK_KEY_4:
                        params.put("pass", BaseConstant.IS_YESNO_NO);
                        break;
                    case InterfaceConstants.DEAL_CAR_FLOW_TASK_KEY_5:
                        params.put("pass", BaseConstant.IS_YESNO_NO);
                        break;
                    case InterfaceConstants.DEAL_CAR_FLOW_TASK_KEY_6:
                        params.put("pass", BaseConstant.IS_YESNO_NO);
                        break;
                }
            }
            if("pass".equals(passCd)){
                // WorkflowClient.setBasePath(PropertiesCacheUtils.getProperty(fl.flow.facade.flow.constant.FlowConstant.FLOW_FLOW_PROPERTIES_FLOW_BASE_URL));
                WorkflowClient.setBasePath(nacosConfiguration.getFlowBaseUrl());
                BaseLogUtils.newLogger("结束转优车工作流参数").setKeys("pInstId:" + pInstId, "taskDefKey:" + taskDefKey).info();
                com.lionbridge.activiti.dto.MessageDTO<String> messageDto = WorkflowClient.completeTaskByTaskDefKey(pInstId, taskDefKey, params);
                BaseLogUtils.newLogger("结束转优车工作流结果").setKeys("messageDto:" + JSON.toJSONString(messageDto)).info();
                if(null != messageDto && messageDto.isSuccess()){
                    // 返回结果:成功
                }else{
                    // 返回结果:失败
                    result.setCode(String.valueOf(BaseConstant.IS_YESNO_NO));
                    result.setInfo("结束转优车工作流处理失败!");
                }
            }
        } catch (BaseException e) {
            result.setCode(String.valueOf(BaseConstant.IS_YESNO_NO));
            result.setInfo("结束转优车工作流异常");
            BaseLogUtils.newLogger("结束转优车工作流异常").setKeys("pInstId:" + pInstId).setThrowable(e).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            e.printStackTrace();
        } catch (Exception e) {
            result.setCode(String.valueOf(BaseConstant.IS_YESNO_NO));
            result.setInfo("结束转优车工作流异常");
            BaseLogUtils.newLogger("结束转优车工作流异常").setKeys("pInstId:" + pInstId).setThrowable(e).setWarning(false).error(LogExceptionEnum.COMMON_CODE_0002);
            e.printStackTrace();
        }
        BaseLogUtils.newLogger("结束转优车工作流结束").setKeys("pInstId:" + pInstId, "taskDefKey:" + taskDefKey, "result:" + JSON.toJSONString(result)).info();
        return result;
    }

    @Override
    public int batchUpdateDealCarFlowAudStatus(List<SysFlowSHDTO> sysFlowSHDTOS) throws BaseException {
        return assDealCarMapper.batchUpdateDealCarFlowAudStatus(sysFlowSHDTOS);
    }

    @Override
    public int modify4Null(AssDealCarDTO entity) throws BaseException {
        return assDealCarMapper.modify4Null(AssDealCarTransform.toPO(entity));
    }
}

